/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrievedefault;

import com.inspur.edp.bef.api.action.VoidActionResult;
import com.inspur.edp.bef.api.be.IBENodeEntityContext;
import com.inspur.edp.bef.core.action.base.ActionUtil;
import com.inspur.edp.bef.core.be.BEManager;
import com.inspur.edp.bef.core.be.BusinessEntity;
import com.inspur.edp.bef.spi.action.AbstractAction;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;

public class FullRetrieveDefaultAction extends AbstractAction<VoidActionResult> {

  private final IEntityData data;
  private BusinessEntity businessEntity;

  public FullRetrieveDefaultAction(IBENodeEntityContext context, IEntityData data) {
    super(context);
    this.data = data;
  }

  @Override
  public void execute() {
//    String dataID = StringUtils.isEmpty(data.getID()) ? UUID.randomUUID().toString() : data.getID();
    businessEntity = ActionUtil.getRootEntity(this);
    ModifyChangeDetail change = buildRootDataChange(data);
    businessEntity.modify(change);
  }

  private ModifyChangeDetail buildRootDataChange(IEntityData data) {
    Map<String, Object> defaultValues = buildDefaultValues(data);
//    String dataID = StringUtils.isEmpty(data.getID()) ? UUID.randomUUID().toString() : data.getID();
    businessEntity.retrieveDefault(defaultValues);
//    setResult(businessEntity.getBEContext().getData());
    ModifyChangeDetail change = buildDataChangeCore(data, new ArrayList<>(),
        Arrays.asList(businessEntity.getID()), businessEntity.getID());
    return change;
  }

  private ModifyChangeDetail buildChildDataChange(IEntityData data,
      List<String> nodePath, List<String> idPath) {
    String dataID = StringUtils.isEmpty(data.getID()) ? UUID.randomUUID().toString() : data.getID();
    Map<String, Object> defaultValues = buildDefaultValues(data);
    businessEntity.retrieveDefaultChild(nodePath, idPath, dataID, defaultValues);
    List<String> childIdPath = new ArrayList<>(idPath);
    childIdPath.add(dataID);
    return buildDataChangeCore(data, nodePath, idPath, dataID);
  }

  private ModifyChangeDetail buildDataChangeCore(IEntityData data,
      List<String> nodePath, List<String> idPath, String dataId) {
    ModifyChangeDetail change = new ModifyChangeDetail(dataId);
//    if(!isRoot) {
//      for (String prop : data.getPropertyNames()) {
//        if ("ID".equalsIgnoreCase(prop)) {
//          continue;
//        }
//        Object newValue = data.getValue(prop);
//        change.putItem(prop,
//            (newValue != null && newValue instanceof IValueObjData) ? InnerUtil
//                .buildNestedChange(newValue) : newValue);
//      }
//    }

    for (Map.Entry<String, IEntityDataCollection> child : data.getChilds().entrySet()) {
      if (child.getValue() == null) {
        continue;
      }
      List<String> childPath = new ArrayList<>(nodePath);
      childPath.add(child.getKey());
      for (IEntityData childData : child.getValue()) {
        change
            .addChildChangeSet(child.getKey(), buildChildDataChange(childData, childPath, idPath));
      }
    }
    return change;
  }

  private Map<String, Object> buildDefaultValues(IEntityData data){
    Set<String> childs = data.getChilds().keySet().stream().map(item -> item.concat("s")).collect(
        Collectors.toSet());
    Map<String, Object> values = new HashMap<>();
    for (String prop : data.getPropertyNames()) {
      if ("ID".equalsIgnoreCase(prop)) {
        continue;
      }
      if(childs != null && childs.contains(prop)){
        continue;
      }
      Object newValue = data.getValue(prop);
      if(newValue instanceof IEntityDataCollection){
        continue;
      }
      values.put(prop, newValue);
    }
    return values;
  }
}
